package mythical.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import dto.UserLoginDto;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import mythical.exceptions.LoginFailedException;
import mythical.mapper.UserMapper;
import mythical.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import po.User;
import vo.UserLoginVO;

@RequiredArgsConstructor
@Service
@Slf4j
public class UseServiceimpl extends ServiceImpl<UserMapper, User> implements UserService {

    /**
     * 用户登录
     * @param userLoginDto
     * @return
     */
    @Override
    public UserLoginVO login(UserLoginDto userLoginDto) {
        User user = lambdaQuery()
                .eq(User::getName, userLoginDto.getName())
                .eq(User::getPassword, userLoginDto.getPassword())
                .one();
        if (ObjectUtil.isEmpty(user)){
            throw new LoginFailedException("用户名或者密码错误！");
        }
        log.info("获取到用户：{}",user);
        StpUtil.login(user.getId());
        UserLoginVO userLoginVO=new UserLoginVO();
        BeanUtils.copyProperties(user,userLoginVO);
        userLoginVO.setToken(StpUtil.getTokenValue());
        return userLoginVO;
    }
}
